package br.com.lambdacore.ui.stripes.exceptionhandler;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sourceforge.stripes.action.ActionBean;
import net.sourceforge.stripes.controller.StripesConstants;
import net.sourceforge.stripes.exception.DefaultExceptionHandler;
import net.sourceforge.stripes.validation.LocalizableError;
import br.com.lambdacore.domain.exception.ILambdaCoreException;
import br.com.lambdacore.validator.Validator;

public class LambdaCoreExceptionHandler extends DefaultExceptionHandler {

	@Override
	public void handle(Throwable throwable, HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		if (Validator.is(throwable).instanceOf(ILambdaCoreException.class)) {
			this.handleILambdaCoreException((ILambdaCoreException) throwable,
					request, response);
		}
	}

	private void handleILambdaCoreException(ILambdaCoreException throwable,
			HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		ActionBean bean = (ActionBean) request
				.getAttribute(StripesConstants.REQ_ATTR_ACTION_BEAN);
		if (bean != null) {
			LocalizableError error = new LocalizableError(
					throwable.getLocalizedMessage(), throwable.getArguments());
			bean.getContext().getValidationErrors().addGlobalError(error);
		}
	}

}
